package cn.pet.service.manage.exception;

import cn.pet.service.manage.entity.api.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {
    private static final String BAD_REQUEST_MSG = "参数错误";

    // <1> 处理 form data方式调用接口校验失败抛出的异常
    @ExceptionHandler(BindException.class)
    public Result bindExceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return Result.error(collect.get(0));
    }

    // <2> 处理 json 请求体调用接口校验失败抛出的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return Result.error(collect.get(0));
    }

//    // <3> 处理单个参数校验失败抛出的异常
//    @ExceptionHandler(ConstraintViolationException.class)
//    public Result constraintViolationExceptionHandler(ConstraintViolationException e) {
//        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
//        List<String> collect = constraintViolations.stream()
//                .map(ConstraintViolation::getMessage)
//                .collect(Collectors.toList());
//        return Result.error(collect.get(0));
//    }

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error("系统错误", e);
        return Result.error("系统错误,请联系管理员");
    }

    @ExceptionHandler(BadCredentialsException.class)
    public Result badCredentialsExceptionHandler(BadCredentialsException e) {
        log.error("系统错误", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public Result runtimeExceptionHandler(BadCredentialsException e) {
        log.error("系统错误", e);
        return Result.error(e.getMessage());
    }


}
